class pageChange {
    constructor(ops) {
        this.url = ops.url || '';
        this.cont = ops.cont || null;
        this.left = ops.left || null;
        this.right = ops.right || null;
        this.pageCon = ops.pageCon || null;
        this.num = ops.num || 3;
        this.index = ops.index || 0;

        // console.log(this.index);

        this.load();
        this.addEvent();
    }
    load() {
        ajaxGet(this.url, (res) => {
            // console.log(res);
            this.res = JSON.parse(res);
            // console.log(this.res);
            this.display();
            this.createPage();
        });
    }
    display() {
        let str = '';
        for (let i = this.index*this.num; i < (this.index+1)*this.num; i++) {
           if(i<this.res.length){
            str += `<li>
                <img src="${this.res[i].url}" alt="" class="img">        
                <h2>商品名称:<span>${this.res[i].name}</span></h2>
                <h2>商品介绍:<span>${this.res[i].tip}</span></h2>
                <h2>商品价格:<span>${this.res[i].price}</span></h2>
                </li>`;
            }
           }
            // console.log(str);
            this.cont.innerHTML=str;
        }
        createPage(){
            // 计算页码
            this.pageNum=Math.ceil(this.res.length/this.num);
            // console.log(this.pageNum);
            let str='';
            for(let i=0;i<this.pageNum;i++){
                str+=`<li>${i+1}</li>`;
            }
            // console.log(str);
            this.pageCon.innerHTML=str;
            this.setActive();
    }
    setActive(){
         for(let i=0;i<this.pageCon.children.length;i++){
             this.pageCon.children[i].className='';
            //  console.log(this.pageCon.children[i]);
         }
         this.pageCon.children[this.index].className='active';
    }
    addEvent(){
        let that=this;
        this.left.onclick=function(){
            // console.log(111);
            if(that.index===0){
                that.index=that.pageNum-1;
            }else{
                that.index--;
            }
            that.setActive();
            that.display();
        }
        this.right.onclick=function(){
            if(that.index===that.pageNum-1){
                that.index=0;
            }else{
                that.index++;
            }
            that.setActive();
            that.display();
        }
    }

}

new pageChange({
    url: 'http://localhost/2003/page/goods.json',
    cont: this.document.getElementById('list'),
    left: document.getElementById('btnL'),
    right: document.getElementById('btnR'),
    pageCon: document.querySelector('#pageWrap ul'),
    num:  3,
    index: 0
})